package service;

import com.fr.base.ConfigManager;
import com.fr.base.FRContext;
import com.fr.base.Parameter;
import com.fr.script.AbstractFunction;
import com.fr.stable.Primitive;
import com.fr.stable.StringUtils;
import com.wondersgroup.hs.mobile.nursing.rpc.service.ReportService;
import com.wondersgroup.hs.mobile.nursing.rpc.utils.ClientServiceFactory;
import com.wondersgroup.hs.report.plugin.utils.GlobalParameterUtils;
import dao.JDBCConn;
import util.ReportError;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;

import static util.ConstantSetUp.passWord;
import static util.ConstantSetUp.url;
import static util.ConstantSetUp.user;

/**
 * Created by Xtra on 3/28 0028.
 */
public class ItemQuery extends AbstractFunction {

    ReportService reportService;

    String serviceURL;

    public ItemQuery() {
        String value = GlobalParameterUtils.getGlobalParameter("ReportServiceURL");
        if (value!=null)
            setServiceURL(value);
    }

    public String getServiceURL() {
        return serviceURL;
    }

    public void setServiceURL(String serviceURL) {

        this.serviceURL = serviceURL;
        try {
            reportService = ClientServiceFactory.service(ReportService.class, new URL(serviceURL));
        }catch (Throwable e){
            throw new ReportError(e);
        }
    }

    @Override
    public Object run(Object[] objects) {
        String result="";
        try {
            String documentID= (String) objects[0];
            String displayTitle= (String) objects[1];
            if(!StringUtils.isEmpty(documentID)||!StringUtils.isEmpty(displayTitle)){
                String sql1 = "select a.c_content from t_mb_emr_docValue a left JOIN t_mb_emr_items b on a.c_item=b.c_itemID where a.c_document='"+documentID+"' AND  c_displayTitle='"+displayTitle+"'";
                JDBCConn jdbcConn=new JDBCConn();
                FRContext.getLogger().log(Level.INFO, "链接数据库192.168.0.60中：---{数据库url:"+ url+",登录名：nurse}!");
                jdbcConn.getConnection(url, user, passWord);
                FRContext.getLogger().log(Level.INFO, "准备执行SQL语句：**{"+sql1+"}!");
                 result = jdbcConn.executeQuery(sql1);
                jdbcConn.close();
            }else{
                FRContext.getLogger().log(Level.WARNING, "SQL执行异常！请检查数据或插件！插件名：plugin-itemQuery");
                return Primitive.ERROR_VALUE;

            }
            FRContext.getLogger().log(Level.INFO, "SQL执行完毕！输出结果！-----"+result);
        } catch (Exception e) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            FRContext.getLogger().log(Level.WARNING, stringWriter.toString());
        }
        return result;
    }
}
